/*
 * Block.cpp
 *
 *  Created on: Apr 19, 2011
 *      Author: dave
 */

#include "Block.h"
#include <bitset>

Block::Block(int number, byte* data) {
	this->number = number;
	this->data = data;

	int a = 0x12345678;
	unsigned char *c = (unsigned char*)(&a);
	if (*c == 0x78){
		this->bigEndian = false;
	}else{
		this->bigEndian = true;
	}
}

Block::~Block(){
//	delete data;
}

int Block::getNumber() {
	return this->number;
}

byte Block::readByte(int offset) {
	if(this->data > 0) {
		//cout << "reading byte at: " << offset << " (" << (int)data[offset] << ")" << endl;
		return this->data[offset];
	}else{
		cout << "?????" << endl;
	}

	return 0;
}

short Block::readShort(int offset) {
	short output;
	char* array = (char*) &output;

	if(this->data > 0) {
		if(this->isBigEndian()) {
			array[0] = this->data[offset];
			array[1] = this->data[offset + 1];
		} else {
			array[0] = this->data[offset + 1];
			array[1] = this->data[offset];
		}
	}
	//cout << "short: " << offset << ": "  << std::bitset<16>( output ) << endl;
	return output;

}

ushort Block::readUShort(int offset) {
	return (unsigned short)readShort(offset);
}

long Block::readLong(int offset) {
	long output;
	char* array = (char*) &output;

	if(this->data > 0) {
		if(this->isBigEndian()) {
			array[0] = this->data[offset];
			array[1] = this->data[offset + 1];
			array[2] = this->data[offset + 2];
			array[3] = this->data[offset + 3];
		} else {
			array[0] = this->data[offset + 3];
			array[1] = this->data[offset + 2];
			array[2] = this->data[offset + 1];
			array[3] = this->data[offset];
		}
	}

	return output;
}

bool Block::isBigEndian() {
	return this->bigEndian;
}
